---@module wenscq
-- 与温氏苍穹相关的对接
require "http"
require "tool"
require "config"
require "deviceConfig"
require "sim"
require "nvm"
module(..., package.seeall)

local function bootstapcbfunc(result, statusCode, head, body)
    log.info("bootstapcbfunc", result, statusCode, body)
    if result == true then
        local json_data, ok = json.decode(body)
        if ok == false then
            log.warn("not json=" .. body)
            return
        end
        if json_data["errorCode"] == "fail" then
            -- 不能自动注册并且获取mqtt连接信息
        else
            -- 正常返回
            -- {
            --    "success": true,
            --    "data": {
            --        "password": "f29b82f145c53e8aa49520cb4befeb449acf7473f4c663b5992ad59cf5ac4cbe",
            --        "clientId": "604094e58054bc02d8476d1d_123456789_0_0_2021041507",
            --        "username": "604094e58054bc02d8476d1d_123456789"
            --    },
            --    "errorCode": "success"
            -- }
            --local password = json_data["data"]["password"]
            local password = "wenswlw300498"
            local clientId = json_data["data"]["clientId"]
            local username = json_data["data"]["username"]
            log.info("mqttinfo", "password=" .. password .. ",clientId=" ..
                         clientId .. ",username=" .. username)
            -- 更新mqtt 连接信息
            deviceConfig.setMqttInfo(clientId, username, password)
        end
        -- sys.publish("ALIYUN_AUTH_IND",result,statusCode,body)
    else
        -- 连接失败
    end

end

-- 开机时通过访问苍穹实现自注册获取连接华为云的信息，
sys.taskInit(function()
    log.info("wesncq taskinit")
    -- 不要省略此处代码，否则下文中的misc.getImei有可能获取不到
    while not socket.isReady() do sys.waitUntil("IP_READY_IND") end
    log.info("wesncq taskinit", "--start http post")
    local iccid = ""
    local linkmode = ""
    if sim.getStatus() == true then iccid = sim.getIccid() end
    local ISW5500 = nvm.get("w5500Used")
    if ISW5500 == true then
        linkmode = "NET"
    else
        linkmode = "SIM"
    end
    local body = {
        imei = misc.getImei(),
        iccid = iccid, -- 对应sim卡的iccid
        linkmode = linkmode, -- 上网方式 NET 有线 SIM 4g
        csp = net.getRssi(),
        version = _G.VERSION,
        frimware = rtos.get_version(),
        product = _G.PROJECT
    }
    local bodystr = json.encode(body)
    log.info("IOT_BOOT_URL send body:", tool.print_dump(body))
    http.request("POST", config.IOT_BOOT_URL, nil,
                 {["Content-Type"] = "application/json;charset=utf-8"}, bodystr,
                 10000, bootstapcbfunc)
end)
